package com.wlyuan.open.scanner.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wlyuan.open.scanner.dao.entity.MConfigDO;
import com.wlyuan.open.scanner.dao.mapper.MConfigMapper;
import com.wlyuan.open.scanner.domain.customer.CustomerConfig;
import com.wlyuan.open.scanner.domain.customer.CustomerConfigConvert;
import com.wlyuan.open.scanner.repository.CustomerConfigRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CustomerConfigRepositoryImpl implements CustomerConfigRepository {
    private final MConfigMapper mConfigMapper;

    @Override
    public CustomerConfig getByCustomerId(Long customerId, Long companyId) {
        LambdaQueryWrapper<MConfigDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MConfigDO::getCfgCustomerid, customerId).orderByDesc(MConfigDO::getCfgCreatetime);
        var data = CustomerConfigConvert.convert(mConfigMapper.selectList(queryWrapper).stream().findFirst().orElse(null));
        return Optional.ofNullable(data).orElse(getByCompanyId(companyId));
    }

    private CustomerConfig getByCompanyId(Long companyId) {
        LambdaQueryWrapper<MConfigDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MConfigDO::getCfgCompanyid, companyId).orderByDesc(MConfigDO::getCfgCreatetime);
        return CustomerConfigConvert.convert(mConfigMapper.selectList(queryWrapper).stream().findFirst().orElse(null));
    }

}
